package org.sqp.wbnet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqp.conn.Browser;
import org.sqp.conn.BrowserFactory;
import org.sqp.wbnet.model.UserInfo;
import org.sqp.wbnet.model.WbAd;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WbNetApplication {
    private static Logger logger = LoggerFactory.getLogger(WbNetApplication.class);

    public static void main(String[] args) {
        if (args.length <2){
            logger.info("请在启动参数添加宽带用户名和密码！ ");
        }
        String bandId = args[0];
        String bandPwd = args[1];
        logger.info("您的宽带用户名[{}]，密码[{}],自动任务已开启，系统将每10分钟运行一次 :) ",bandId,bandPwd);

        ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutor.scheduleAtFixedRate(() -> once(bandId, bandPwd), 0, 10, TimeUnit.MINUTES);
    }

    private static void once(String bandId, String bandPwd) {
        Browser chrome = BrowserFactory.getDefaultBrowser();
        WbActions.index(chrome);
        String sid = WbActions.login(chrome, bandId, bandPwd);
        chrome.addCookie("hlwb_sid", sid, "www.cpwbnet.com", "/");
        List<WbAd> ads = WbActions.getAds(chrome);
        if (sid == null || "".equals(sid.trim())) {
            logger.info("登录失败!");
            return;
        }
        logger.info("登录成功! "+sid);
        UserInfo ui1 = WbActions.getUserInfo(chrome, sid);
        logger.info("{}的{}宽带[{}]，查询前到期时间{}", ui1.getName(), ui1.getBandWitth(), ui1.getAccId(), ui1.getDisDate());


        ads.forEach(ad -> {
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.debug("req " + ad.getImageId());
            WbActions.credit(chrome, sid, ad);
        });

        UserInfo ui = WbActions.getUserInfo(chrome, sid);
        logger.info("{}的{}宽带[{}]，到期时间为{}", ui.getName(), ui.getBandWitth(), ui.getAccId(), ui.getDisDate());
    }
}
